<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showConfirmDialog, showFailToast, showSuccessToast, showLoadingToast, Toast, showToast } from "vant";
import QRCode from "@/components/my/qrCode.vue";
import api from "@/api/api";
import { Decimal } from "decimal.js";
import 'vant/es/toast/style'; // 引入Toast样式

// 引入图片资源
import phoneIcon from '@/assets/my/phone.png'
import dhIcon from '@/assets/my/dh.png'

// 响应式数据
const src = ref("")
const phoneNumber = ref("10086")
const showMap = ref(false)
const actions = ref([{ name: "高德地图" }])
const type = ref(0)
const orderType = ref(-1)
const orderSn = ref("")
const orderInfo = ref({})
const storeInfo = ref({})
const totalPrice = ref(0)
const loading = ref(true)

// DOM引用
const qrRef = ref(null)

// 路由
const route = useRoute()
const router = useRouter()

// 计算属性
const title = computed(() => {
  if (type.value == 0) {
    return "待付款";
  } else if (type.value === 1) {
    return "支付中";
  } else if (type.value === 2) {
    return "已付款";
  } else if (type.value === 3) {
    return "退款中";
  } else if (type.value === 11) {
    return "待自提";
  } else if (type.value === 21) {
    return "待发货";
  } else if (type.value === 22) {
    return "待收货";
  } else if (type.value === 31) {
    return "待核销";
  } else if (type.value === 8) {
    return "待评价";
  } else if (type.value === 4) {
    return "待退款";
  } else if (type.value === 99) {
    return "已取消";
  } else if (type.value === 100) {
    return "已完成";
  }
  return "";
})

const afterSaleTitle = computed(() => {
  if (orderInfo.value.serviceStatus == 0) {
    return "申请中";
  } else if (orderInfo.value.serviceStatus === 11) {
    return "已通过";
  } else if (orderInfo.value.serviceStatus === 12) {
    return "已拒绝";
  } else if (orderInfo.value.serviceStatus === 13) {
    return "待卖家收货";
  } else if (orderInfo.value.serviceStatus === 14) {
    return "卖家确认收货";
  } else if (orderInfo.value.serviceStatus === 15) {
    return "卖家终止售后";
  } else if (orderInfo.value.serviceStatus === 1) {
    return "买家取消售后";
  } else if (orderInfo.value.serviceStatus === 16) {
    return "等待平台退款";
  } else if (orderInfo.value.serviceStatus === 100) {
    return "已完成";
  }
  return "";
})

// 方法定义
const onClickLeft = () => {
  router.back();
}

const refreshQRCode = async () => {
  await qrRef.value.generateQRCode();
  showSuccessToast('刷新二维码成功');
}

const goToPhone = (phone) => {
  window.location.href = `tel:${phone}`;
}

const goToAdress = () => {
  showMap.value = true;
}

const onSelect = (item, index) => {
  console.log(item, index);
  if (index == 0) {
    openGDMap();
  }
  onClose();
}

const onClose = () => {
  showMap.value = false;
}

const goRefund = () => {
  router.push({
    path: "/refund",
    query: {
      sn: orderSn.value,
    },
  });
}

const chat = () => {
  router.push({
    path: "/customer",
  });
}

const pay = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  });
  let res = await api.pay.pay({
    sn: orderSn.value,
  });
  if (res) {
    Toast.close(); // 替代 Toast.clear()
    window.location.href = res;
  } else {
    showFailToast('支付失败');
  }
}

const openGDMap = () => {
  const iosScheme = `iosamap://poi?sourceApplication=zxcxapp&name=${storeInfo.value.address}&lat1=&lon1=&lat2=&lon2=&dev=0`;
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.src = iosScheme;
  document.body.appendChild(iframe);
  setTimeout(() => {
    document.body.removeChild(iframe);
  }, 500);
}

const openBDMap = () => { }

const openTXMap = () => { }

const getOderDetail = async () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  let res = {};
  if (orderType.value == 4) {
    res = await api.order.getAfterSaleInfo({
      sn: orderSn.value,
    });
  } else {
    res = await api.order.orderDetail({
      orderSn: orderSn.value,
    });
  }

  loading.value = false;

  orderInfo.value = res;
  type.value =
    orderType.value != 4
      ? orderInfo.value.order.orderStatus
      : orderInfo.value.serviceStatus;
  if (orderType.value != 4) {
    storeInfo.value = await api.store.getStoreDetail({
      shopId: res.order.storeId,
    });
    let totalprice = new Decimal("0");
    orderInfo.value.orderItems.forEach((e) => {
      let price = new Decimal(String(e.subTotal));
      totalprice = totalprice.plus(price);
    });
    totalPrice.value = totalprice.toString();
    await getQRUrl();
  }
}

const copy = (e) => {
  let value = e;
  var input = document.createElement("input");
  //将input的值设置为需要复制的内容
  input.value = value;
  //添加input标签
  document.body.appendChild(input);
  //选中input标签
  input.select();
  //执行复制
  document.execCommand("copy");
  //移除input标签
  document.body.removeChild(input);
  showSuccessToast('复制成功');
}

const comment = () => {
  router.push({
    path: "/comment",
    query: {
      sn: orderSn.value,
      orderItemSn: orderInfo.value.orderItems[0].orderSn,
    },
  });
}

const getQRUrl = async () => {
  if (type.value == 31) {
    let res = await api.order.getTicket({
      orderSn: orderSn.value,
      orderItemSn: orderInfo.value.orderItems[0].sn,
    });
    src.value = `https://axxuser.cxepsp.com/#/writeOfforder?code=${res.skuInfoList[0].code}&storeId=${res.storeInfo.id}`;
  }
}

const cancelAfterSale = () => {
  showConfirmDialog({
    message: "是否取消售后?",
  })
    .then(async () => {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
      });
      await api.order.cancelAfterSale({
        afterSaleSn: orderInfo.value.sn,
      });
      // 移除了 Toast.close() 的调用
      showSuccessToast('取消售后成功');
      await getOderDetail();
    }).catch(() => { })
}

// 生命周期钩子
onMounted(() => {
  orderSn.value = route.query.orderSn;
  orderType.value = route.query.type;
  getOderDetail();
})
</script>

<template>
  <div v-show="!loading" class="orderDetail">
    <van-nav-bar :title="orderType != 4 ? title : afterSaleTitle" fixed />
    <div v-if="type == 31" class="pic">
      <QRCode v-if="src" ref="qrRef" :url="src"></QRCode>
    </div>
    <div class="order_info">
      <div v-if="orderType != 4" class="title">
        <div class="name flex">
          <div class="store_type">服务门店</div>
          <div class="store_name">{{ orderInfo.order?.storeName }}</div>
        </div>
        <div class="icons">
          <van-image class="phone" @click="goToPhone(storeInfo.phone)" :src="phoneIcon" />
        </div>
      </div>
      <div v-if="type != 3 && type != 4 && orderType != 4" class="address">
        <van-icon name="location-o" style="margin-right: 5px" />
        <span>门店地址：{{ storeInfo.address }}</span>
        <div class="icons">
          <van-image class="dh" :src="dhIcon" @click="goToAdress()" />
        </div>
      </div>
      <template v-if="orderType != 4">
        <div v-for="(v, i) in orderInfo.orderItems" :key="i" class="info">
          <div class="info_left">
            <van-image class="left_icon" :src="v.image" />
            <div class="serve_name van-multi-ellipsis--l2">
              {{ v.goodsName }}
            </div>
          </div>
          <div class="info_right">
            <div class="right_price">￥{{ v.skuPrice }}</div>
            <div class="right_num">x{{ v.num }}</div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="orderSn">
          <span class="sn_tips">商品名称：</span>
          <span class="order_sn">{{ orderInfo.goodsName }}</span>
        </div>
        <div class="orderSn">
          <span class="sn_tips">商品总价：</span>
          <span class="order_sn">¥{{ orderInfo.flowPrice }}</span>
        </div>
        <div class="orderSn">
          <span class="sn_tips">申请退款金额</span>
          <span class="order_sn">¥{{ orderInfo.applyRefundPrice }}</span>
        </div>
      </template>
      <div v-if="orderType != 4" class="price right_pos">
        订单总价：￥{{ orderType != 4 ? totalPrice : orderInfo.flowPrice }}元
      </div>
      <div>
        <div v-if="type == 0 && orderType != 4" class="discount right_pos">
          <span class="text_2">需付款 ￥{{ totalPrice }}元</span>
        </div>
        <div v-if="type == 2 && orderType != 4" class="discount right_pos">
          <span class="text_2">已支付 ￥{{ totalPrice }}元</span>
        </div>
      </div>
      <div class="orderSn">
        <span class="sn_tips">订单号：</span>
        <span class="order_sn">{{ orderType != 4 ? orderInfo.order?.sn : orderInfo.sn }}
          <span class="copy" @click="copy(orderType != 4 ? orderInfo.order?.sn : orderInfo.sn)">复制</span></span>
      </div>
      <div class="orderSn">
        <span class="sn_tips">创建时间：</span>
        <span class="order_sn">{{
          orderType != 4 ? orderInfo.order?.createTime : orderInfo.createTime
        }}</span>
      </div>
    </div>
    <div class="btns">
      <div v-if="orderInfo.allowOperationVO?.pay" class="btns_1" @click="pay">
        立即付款
      </div>
      <div v-if="orderInfo.allowOperationVO?.cancel" class="btns_1 red">
        取消订单
      </div>
      <div v-if="type > 0" class="btns_1" @click="chat">联系客服</div>
      <div v-if="type == 31" class="btns_2 red" @click="goRefund">申请退款</div>
      <div v-if="orderInfo.allowOperationVO?.evaluate" class="btns_1" @click="comment">
        去评价
      </div>
      <div v-if="orderType == 4 && orderInfo.serviceStatus == 0" class="btns_2 red" @click="cancelAfterSale">
        取消售后
      </div>
    </div>
    <van-action-sheet v-model:show="showMap" :actions="actions" @select="onSelect" @close="onClose" />
  </div>
</template>



<style lang="less" scoped>
.orderDetail {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/4431a33cd62f4efc9fc53a7606eee382.png") no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  box-sizing: border-box;
  padding: 200px 50px 150px 50px;

  :deep(.van-nav-bar__content) {
    height: 100px;
    margin: 25px auto;
  }

  :deep(.van-nav-bar__title) {
    font-size: 54px;
    font-weight: 500;
  }

  :deep(.van-ellipsis) {
    overflow: initial;
  }

  :deep(.van-nav-bar__left) {
    left: 30px;
  }

  .pic {
    width: 100%;
    padding: 80px 0 80px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .refresh {
      display: flex;
      align-items: center;
      margin-top: 20px;

      span {
        font-size: 38px;
        color: #666666;
        margin-left: 20px;
      }
    }
  }

  .black {
    color: #000;
    font-size: 60px;
  }

  .red_text {
    color: #bd3023;
    font-size: 80px;
    margin-left: 30px;
  }

  .flex {
    display: flex;
    align-items: center;
  }

  .order_info {
    padding: 50px;
    background: #fff;
    border-radius: 25px;
    margin-bottom: 30px;

    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .name {
        font-size: 50px;
        font-weight: bold;
        align-items: flex-start;
        flex-basis: 100%;

        .store_type {
          padding: 3px 10px;
          border-radius: 2px;
          font-size: 34px;
          color: #fff;
          background: #058efb;
          margin-right: 10px;
          text-align: center;
          flex: 2;
        }

        .store_name {
          flex: 11;
          margin-left: 20px;
          font-size: 50px;
        }
      }
    }

    .icons {
      flex: 1;
      display: flex;
      align-items: center;
      margin-left: 20px;
      justify-content: flex-end;

      .phone {
        width: 50px;
        height: 50px;
      }

      .dh {
        width: 59px;
        height: 59px;
        margin-left: 40px;
      }
    }

    .address {
      display: flex;
      align-items: flex-start;
      font-size: 38px;
      color: #333;
      margin-top: 20px;
      margin-bottom: 80px;
    }

    .info {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-top: 20px;

      .info_left {
        display: flex;
        align-items: flex-start;

        .left_icon {
          width: 200px;
          height: 200px;
        }

        .serve_name {
          font-size: 40px;
          color: #888888;
          margin-left: 30px;
          max-width: 700px;
        }
      }

      .info_right {

        .right_price,
        .right_num {
          font-size: 40px;
          color: #888;
          text-align: right;
        }
      }
    }

    .price {
      font-size: 46px;
      color: #333333;
    }

    .right_pos {
      width: 100%;
      text-align: right;
      padding: 10px 0;
    }

    .discount {
      font-size: 42px;

      .text_1 {
        color: #333;
      }

      .text_2 {
        color: #666;
        margin-left: 20px;
      }
    }

    .orderSn {
      margin-top: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .sn_tips {
        font-size: 40px;
        color: #333;
      }

      .order_sn {
        font-size: 40px;
        color: #888888;

        .copy {
          color: #058efb;
          margin-left: 30px;
        }
      }
    }
  }

  .btns {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 80px;

    &_1,
    &_2 {
      color: #fff;
      font-size: 48px;
      padding: 10px 20px;
      border-radius: 15px;
      letter-spacing: 3px;
      background: #058efb;
      margin: 0 15px;
    }

    .red {
      background: #bd3023;
    }
  }

  /deep/ .van-icon {
    font-size: 50px;
    font-weight: bold;
    color: #333333;
  }
}
</style>
